package com.bolang.onlycode.demo.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class NIOClientOne {
    public static void main(String[] args) throws IOException {
        // 得到一个通道
        SocketChannel socketChannel =SocketChannel.open();
        // 设置通道为非阻塞
        socketChannel.configureBlocking(false);
        // 提供服务端的ip和端口
        InetSocketAddress inetSocketAddress=new InetSocketAddress("127.0.0.1",7778);
        // 连接服务器，非阻塞情况下，需要调用finishConnect
        if(!socketChannel.connect(inetSocketAddress)){
            while (!socketChannel.finishConnect()){
                System.out.println("connect...");
            }
        }
        // 如果连接成功,就发送数据
        String str="hello world";
        ByteBuffer buffer=ByteBuffer.allocate(str.length());
        buffer.put(str.getBytes(StandardCharsets.UTF_8));
        // 将数据写入channel
        socketChannel.write(buffer);
        socketChannel.shutdownOutput();
        System.out.println("数据已经写给服务器");
        ByteBuffer buffer2=ByteBuffer.allocate(str.length());
        int len;
        while((len = socketChannel.read(buffer2)) != -1){
            buffer2.flip();
            System.out.println("from Server:"+new String(buffer2.array()).trim());
            buffer2.clear();
        }
        socketChannel.close();
    }
}
